// pages/bbhj_index/bbhj_index.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify';
import {
  host
} from '../../config'
var util = require('../../utils/util.js');
import {
  areaList
} from '../../miniprogram_npm/@vant/area-data';

const urlCal = host + 'cal';
console.log(urlCal);
var app = getApp();
// app.globalData.openid = 'oqgSW5N0XdfRdJYkwgSHLql3hU6Q'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tab_active: 'search',
    // 是否有openid
    haveOpenID: false,
    // 控制显示页面的
    active: 0,

    // 失踪儿童预测面板部分的变量
    areaList: areaList,
    radio_sex: '1',
    city_choose: '请选择城市',
    // 选择框相关的变量
    cityShow: false,
    birthDayShow: false,
    misDayShow: false,
    currentDate: new Date().getTime(),
    minBirthDate: new Date(1990, 0, 1).getTime(), // 一月份从0开始算
    maxBirthDate: new Date().getTime(),
    birth_date: '请选择出生日期',
    minMisDate: new Date(1990, 0, 1).getTime(), // 一月份从0开始算
    maxMisDate: new Date().getTime(),
    mis_date: '请选择失踪日期',
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    // 身高信息
    high_split_result: ["未知", "30cm~43cm", "43cm~56cm",
      "56cm~73cm", "73cm~95cm", "95cm~130cm", "130cm~180cm", "180cm及以上"
    ],
    high_msg: "请选择身高",
    high_index: 0, // 选择的下标，默认为0，也就是未知
    highShow: false,
    // 输入的其他信息
    otherMessage: '',


    // 预测报告部分的变量
    activeNames: [],
    test_loop: [1, 2, 3],
    // 待会改这里
    have_local_report: false,
    debug:true,
    local_report: {
      "name": "2021-05-14 09:03:22",
      "_id": "local_report",
      "time": "2021-05-14 09:03:22",
      "input": {
        "sex": "男",
        "mis_area": "北京市-北京市-北京市",
        "birth_date": "2021-05-13",
        "mis_date": "2021-05-13",
        "high": "未知",
        "other": "三甲医院"
      },
      "report": {
        "_1": {
          "city": "北京市",
          "prob": "0.67461"
        },
        "_2": {
          "city": "常德市",
          "prob": "0.14869"
        },
        "_3": {
          "city": "天津市",
          "prob": "0.05087"
        },
        "_4": {
          "city": "广州市",
          "prob": "0.04230"
        },
        "_5": {
          "city": "保定市",
          "prob": "0.03091"
        },
        "_6": {
          "city": "上海市",
          "prob": "0.01686"
        },
        "_7": {
          "city": "宿州市",
          "prob": "0.01110"
        },
        "_8": {
          "city": "深圳市",
          "prob": "0.00842"
        },
        "_9": {
          "city": "邯郸市",
          "prob": "0.00830"
        },
        "_10": {
          "city": "莆田市",
          "prob": "0.00794"
        }
      }
    },
    change_report_show: false,
    newReportName: ''

  },
  // 打开下拉框
  onCollapseChange(event) {
    console.log('?');
    console.log(event.detail);
    this.setData({
      activeNames: event.detail,
    });
  },

  // 城市选择弹窗相关的 展示，关闭，确认操作
  showCity() {
    this.setData({
      cityShow: true
    });
  },
  onCityClose() {
    this.setData({
      cityShow: false
    });
  },
  onCityFinish(e) {
    // console.log(e);
    var city_choose = [e.detail.values[0].name,
      e.detail.values[1].name,
      e.detail.values[2].name
    ];
    city_choose = city_choose.join('-');
    this.setData({
      city_choose: city_choose,
      cityShow: false
    })
  },

  // 出生日期选择弹窗相关的 展示，关闭，确认操作
  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },
  showBirth() {
    this.setData({
      birthDayShow: true
    });
  },
  onBirthClose() {
    this.setData({
      birthDayShow: false
    });
  },
  onBirthFinish(e) {
    // e.detail是13位置时间戳
    console.log(e.detail);
    var date = new Date(e.detail);
    var date_choose = [date.getFullYear(),
      (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1),
      date.getDate()
    ].join('-');
    console.log(date_choose);
    this.setData({
      birth_date: date_choose,
      birth_date_timestamp: date.getTime(),
      birthDayShow: false
    })
  },

  // 城市选择弹窗相关的 展示，关闭，确认操作
  showMis() {
    this.setData({
      misDayShow: true
    });
  },
  onMisClose() {
    this.setData({
      misDayShow: false
    });
  },
  onMisFinish(e) {
    // e.detail是13位置时间戳
    console.log(e.detail);
    var date = new Date(e.detail);
    var date_choose = [date.getFullYear(),
      (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1),
      date.getDate()
    ].join('-');
    console.log(date_choose);
    this.setData({
      mis_date: date_choose,
      mis_date_timestamp: date.getTime(),
      misDayShow: false
    })
  },
  showHigh() {
    this.setData({
      highShow: true
    });
  },
  onHighClose() {
    this.setData({
      highShow: false
    });
  },
  onHighFinish(e) {
    console.log(e);
    this.setData({
      highShow: false,
      high_msg: e.detail.value,
      high_index: e.detail.index
    });
  },
  onOtherChange(e) {
    // console.log(e);
    this.setData({
      otherMessage: e.detail
    })
  },
  onConfirm(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    Toast(`当前值：${value}, 当前索引：${index}`);
  },

  onCancel() {
    Toast('取消');
  },

  // 身高信息的单向绑定
  inputHigh(e) {
    var value = e.detail.value;
    this.setData({
      inputHigh: value
    });
    console.log(this.data.inputHigh);
  },


  onSexChange(event) {
    console.log(event.detail);
    this.setData({
      radio_sex: event.detail,
    });
  },




  formSubmit: function (e) {
   
    var that = this;
    if (this.data.debug) {
      var radio_sex = '1';
      var city = '北京市-北京市-北京市';
      var birth_date = '2021-05-13';
      var mis_date = '2021-05-13';
      var high_msg = '未知';
      var high_index = 0;
      var otherMessage = '三甲医院'
    } else {
      var radio_sex = this.data.radio_sex;
      var city = this.data.city_choose;
      var birth_date = this.data.birth_date;
      var mis_date = this.data.mis_date;
      var high_msg = this.data.high_msg;
      var high_index = this.data.high_index;
      var otherMessage = this.data.otherMessage
    }


    if (city == '请选择城市') {
      Toast.fail({
        message: '请选择城市',
        forbidClick: true,
        loadingType: 'spinner',
        duration: 1000
      });
      //  return;
    }

    if (birth_date == '请选择出生日期') {
      Toast.fail({
        message: '请选择出生日期',
        forbidClick: true,
        loadingType: 'spinner',
        duration: 1000
      });
      return;
    }

    if (mis_date == '请选择失踪日期') {
      Toast.fail({
        message: '请选择失踪日期',
        forbidClick: true,
        loadingType: 'spinner',
        duration: 1000
      });
      return;
    }

    // console.log(this.data.mis_date_timestamp, this.data.birth_date_timestamp);
    // console.log(this.data.mis_date_timestamp < this.data.birth_date_timestamp);
    if (this.data.mis_date_timestamp < this.data.birth_date_timestamp) {
      Toast.fail({
        message: ' 失踪日期早于出生日期',
        forbidClick: true,
        loadingType: 'spinner',
        duration: 2000
      });
      return;
    }


    if (high_msg == '请选择身高') {
      Toast.fail({
        message: '请选择身高',
        forbidClick: true,
        loadingType: 'spinner',
        duration: 1000
      });
      return;
    }

    console.log([
      radio_sex, // this.data.radio_sex,
      city, //this.data.city_choose,
      birth_date, //this.data.birth_date,
      mis_date, //this.data.mis_date,
      high_index, //this.data.high_index,
      otherMessage //this.data.otherMessage
    ])

    Toast.loading({
      message: '预测中',
      forbidClick: true,
    });

    wx.request({
      url: urlCal,
      data: {
        sex: radio_sex, // 1男 2女
        mis_area: city,
        birth_date: birth_date,
        mis_date: mis_date,
        high: high_index,
        other: otherMessage
      },
      method: 'post',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        console.log(res);
        var sex = '女'
        if (Number(radio_sex) == 1) {
          sex = '男'
        }
        var date = new Date();
        var report_name = [date.getFullYear(),
          (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1),
          date.getDate()
        ].join('-') + ' ' + [
          date.getHours() < 10 ? '0' + date.getHours() : date.getHours(),
          date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(),
          date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds(),
        ].join(':');
        var input_message = {
          'sex': sex, // 1男 2女
          'mis_area': city,
          'birth_date': birth_date,
          'mis_date': mis_date,
          'high': high_msg,
          'other': otherMessage
        }
        var report = {
          'name': report_name,
          'time': report_name,
          'input': input_message,
          'report': JSON.parse(res.data).message
        }


        if (app.globalData.openid) {
          console.log('上传云服务器');
          const db = wx.cloud.database();
          db.collection('bbhj').add({
            data: {
              report: JSON.stringify(report)
            },
            success: res => {
              // 在返回结果中会包含新创建的记录的 _id
              report._id = res._id;
              Notify({
                type: 'primary',
                message: '预测成功',
                duration: 1000
              });
              Toast.success({
                message: '预测成功，结果保存到云端',
                forbidClick: true,
              });
              console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
            },
            fail: err => {
              Notify({
                type: 'danger',
                message: '网络异常',
                duration: 1000
              });
              Toast.success({
                message: '预测成功，结果保存到本地',
                forbidClick: true,
              });
              var local_report = report;
              local_report._id = 'local_report';

              that.setData({
                have_local_report: true,
                local_report: local_report
              })
              console.error('[数据库] [新增记录] 失败：', err)
            }
          })

        } else {

          // console.log((res.data));
          // console.log(JSON.parse(res.data));

          // 本地报告 的意思
          var local_report = report;
          local_report._id = 'local_report';

          that.setData({
            have_local_report: true,
            local_report: local_report
          })
          Notify({
            type: 'primary',
            message: '预测成功',
            duration: 1000
          });
          Toast.success({
            message: '预测成功，结果保存到本地',
            forbidClick: true,
          });
          console.log(local_report);
          console.log(JSON.stringify(local_report));
        }
      }
    })

    console.log(urlCal);
  },
  // 底栏切换
  onBarChange(e) {
    console.log(e);
  },

  // 标签切换
  onTabChange(e) {
    var that = this;
    console.log(e.detail.index);
    // 切换到预测报告页面，如果有openid的话就去请求数据库
    if (Number(e.detail.index) == 1 && app.globalData.openid) {
      const db = wx.cloud.database()
      // 查询当前用户所有的 counters
      db.collection('bbhj').where({
        _openid: app.globalData.openid
      }).get({
        success: res => {
          console.log('[数据库] [查询记录] 成功: ', res)
          console.log(res.data)

          var db_array = new Array();

          for (var item in res.data) {
            each = res.data[item]
            var now_id = each['_id'];
            var report = JSON.parse(each['report']);
            report._id = now_id
            console.log(now_id, report);
            db_array[item] = report;
            // 不知道为什么加上这一层循环才能运行上面一层的循环
            for (var each in item) {}
          }
          console.log(db_array);
          // 保存数据库查询的结果
          that.setData({
            db_array: db_array,
            haveOpenID: true
          })
        },
        fail: err => {

          console.error('[数据库] [查询记录] 失败：', err)
        }
      })
    }
  },

  onReportOpen(e) {
    // 获取操作方向和名字
    // console.log(e);
    var that = this;
    console.log(e.detail);
    const {
      position,
      instance,
      name
    } = e.detail;
    switch (position) {
      // 改名
      case 'left':
        this.setData({
          change_report_show: true,
          //  需要改名的那个元素id，当有很多预测结果的时候用
          need_change_report_id: name,
          newReportName: '',
          change_report_instance: instance
        })

        break;
      case 'right':
        wx.showModal({
          title: '提示',
          content: '确定要删除该报告吗',
          success(res) {
            if (res.confirm) {
              // 如果是本地报告, 就修改是否显示本地报告就行了
              if (name == 'local_report')
                that.setData({
                  have_local_report: false
                })
              // 如果不是本地报告，就根据名字循环找
              else {
                var db_array = that.data.db_array;
                for (var index in db_array) {
                  // 找到报告后，先本地删除，再数据库删除
                  if (db_array[index]._id == name) {
                    console.log(db_array[index], name);
                    db_array.splice(index, 1);
                    that.setData({
                      db_array: db_array
                    })
                    const db = wx.cloud.database()
                    db.collection('bbhj').doc(name).remove({
                      success: res => {
                        console.log('[数据库] [删除记录] 成功：', res)
                      },
                      fail: err => {
                        console.error('[数据库] [删除记录] 失败：', err)
                      }
                    })
                  }
                }
              }
            } else if (res.cancel) {
              // console.log('用户点击取消')
            }
            instance.close();
          }
        })

        break;
    }
  },
  onChangeReportClose() {
    this.setData({
      change_report_show: false,
    })
    this.data.change_report_instance.close();
  },
  inputNewReport(e) {
    this.setData({
      newReportName: e.detail
    })
  },
  onChangeReportSave(e) {
    var newName = this.data.newReportName.trim();
    if (newName == '') {
      Toast.fail({
        message: '报告名称不能为空',
        forbidClick: true,
        loadingType: 'spinner',
        duration: 1000
      });
      return;
    } else {

      // 如果是本地报告
      if (this.data.need_change_report_id == 'local_report') {
        this.setData({
          ['local_report.name']: newName,
          change_report_show: false,
        })
      }
      // 如果不是本地报告，就根据名字循环找
      else {
        var db_array = this.data.db_array;
        var need_change_index = 0;
        var report = 0;
        for (var index in db_array) {
          // 找到报告
          if (db_array[index]._id == this.data.need_change_report_id) {
            need_change_index = index;
            report = db_array[index];
          }
        }
        // 先本地删除，再数据库删除
        console.log(`db_array[${need_change_index}].name`);
        this.setData({
          [`db_array[${need_change_index}].name`]: newName,
          change_report_show: false,
        })
        console.log(report);
        console.log(report.name);
        report.name = newName;
        const db = wx.cloud.database();
        db.collection('bbhj').doc(this.data.need_change_report_id).update({
          data: {
            report: JSON.stringify(report)
          },
          success: res => {
            console.log('[数据库] [更新记录] 成功', res);
          },
          fail: err => {
            console.error('[数据库] [更新记录] 失败：', err)
          }
        })
      }
      // 关闭滑块
      this.data.change_report_instance.close();
    }
  },
  onShow: function (options) {
    // 有问题，删除报告后图表就不显示了
    this.getTabBar().init();
    this.setData({
      activeNames: []
    })
    if (app.globalData.openid) {
      this.setData({
        haveOpenID: true
      })
    }
    var that = this;
    if (app.globalData.openid && !this.data.db_array) {
      const db = wx.cloud.database()
      // 查询当前用户所有的 counters
      db.collection('bbhj').where({
        _openid: app.globalData.openid
      }).get({
        success: res => {
          console.log('[数据库] [查询记录] 成功: ', res)
          console.log(res.data)

          var db_array = new Array();

          for (var item in res.data) {
            each = res.data[item]
            var now_id = each['_id'];
            var report = JSON.parse(each['report']);
            report._id = now_id
            console.log(now_id, report);
            db_array[item] = report;
            // 不知道为什么加上这一层循环才能运行上面一层的循环
            for (var each in item) {}
          }
          console.log(db_array);
          // 保存数据库查询的结果
          that.setData({
              db_array: db_array,
              haveOpenID: true
            }),

            // 保存到全局变量，方便查询使用
            app.globalData.db_array = db_array;
        },
        fail: err => {
          console.error('[数据库] [查询记录] 失败：', err)
        }
      })
    }

  },
  onHide: function () {
    // 这个页面不再显示的时候，就把当前的local_report和db_array保存起来
    if (this.data.have_local_report) {
      app.globalData.local_report = this.data.local_report;
    }
    else{
      app.globalData.local_report = undefined;
    }
    app.globalData.db_array = this.data.db_array;
    // console.log(app.globalData.local_report, app.globalData.db_array)
  },
  onUnload() {
    app = null; //记得释放
  }

})